//
//  M_HelperVC.swift
//  letuofu
//
//  Created by WH-JS on 2020/3/25.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit
import MJRefresh

class M_HelperVC: BaseViewControllerWithHeader,UITableViewDelegate,UITableViewDataSource {
    var selLab = ""
    var lables = [String]()
    var sysqaList = [[String:Any?]]()
    var tabList = M_HelpLabList()
    
    var tableView = UITableView(frame: CGRect.zero, style: .plain)
    var tableList = [[String:Any?]]()
    
    var pageIndex = 1
    var allCount = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        getLables(callback: { (s,labs) in
            self.tabList.listAry = labs ?? []
        })

        pageIndex = 1
        allCount = 0
        self.getSysqaList(lables: nil, callback: { (sec,list) in
            if sec {
                self.tableList = list
                self.tableView.reloadData()
            }
        })
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    
    func getLables(callback: @escaping (Bool,[String]?) -> Void) {
        API.formRequest(url: .YI_GetLables, params: ["lableType": 2], callback: { (result) in
        if result.success {
            if let dl = result.data?.getString("lables") {
                callback(true, dl.components(separatedBy: ","))
           }
           else {
               callback(false,nil)
            }
        }else{
            callback(false,nil)
        }
            
        })
    }
    
    func getSysqaList(lables: String?,callback: @escaping (Bool,[[String:Any?]]) -> Void) {
        var params :[String:Any]?
        if lables != nil {
            params = ["lables": lables ?? "","pageIndex": pageIndex]
        }
        API.formRequest(url: .YI_GetSysqaList, params: params, callback: { (result) in
            if result.success {
                self.allCount = result.data?.getInt("allCount") ?? 0
                if let dl = result.data?.getDictList("data") {
                    if self.pageIndex == 1 {
                        callback(result.success, dl)
                    }
                    else {
                        let list = self.tableList + dl
                        callback(result.success, list)
                    }
                }
                else {
                    callback(result.success, self.tableList)
                }
            }

            let _ = self.getRefreshFooter()
        })
    }
    
    func getSysqaById(id: Int,callback: @escaping (Bool,[String:Any?]) -> Void) {
        let params :[String:Any] = ["id": id]
        API.formRequest(url: .YI_GetSysqaById, params: params) { (result) in
            if let dl = result.data?.getDictionary("data") {
                callback(result.success,dl)
            }
        }
    }
}

// MARK: UI
extension M_HelperVC {
    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
        view.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        headTitle.text = "帮助"

        //画横线
        let line = headView.drawView { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        safeView.drawView(view: tabList) { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(headView.snp.bottom)
            make.height.equalTo(150)
        }
        tabList.backgroundColor = .xF2F2F2
        tabList.titleLabel.text = "帮助标签"
        tabList.callDelBlock {
        }
        tabList.callMoreBlock {
        }
        tabList.tagsView.addTapGRToBoxes(callback: { (s) in
            self.selLab = s
            self.pageIndex = 1
            self.allCount = 0
            self.getSysqaList(lables: s, callback: { (sec,list) in
                if sec {
                    self.tableList = list
                    self.tableView.reloadData()
                }
            })
        })
        
        
        safeView.addSubview(tableView)
        tableView.backgroundColor = .white;
//        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(tabList.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
        func getRefreshHeader()->MJRefreshHeader {
    //        顶部的下拉初始化
            let header = MJRefreshNormalHeader()
            header.lastUpdatedTimeLabel.isHidden = true
            tableView.mj_header = header
            header.setTitle("下拉刷新...", for: .idle)
            header.setTitle("下拉刷新...", for: .pulling)
            header.setTitle("下拉更新中...", for: .refreshing)
            header.setTitle("完成...", for: .willRefresh)
            header.setTitle("下拉刷新...", for: .noMoreData)
            header.setRefreshingTarget(self, refreshingAction: #selector(onHeaderRequery))

    //        顶部的处理逻辑：
            return tableView.mj_header!
        }
        
        func getRefreshFooter()->MJRefreshFooter {
            if tableView.mj_footer == nil {
                //        底部初始化：
                let footer = MJRefreshAutoNormalFooter()
    //            footer.isOnlyRefreshPerDrag = true
                tableView.mj_footer = footer
                footer.setTitle("上拉更多...", for: .idle)
                footer.setTitle("上拉更多...", for: .pulling)
                footer.setTitle("下拉更新中...", for: .refreshing)
                footer.setTitle("", for: .willRefresh)
                footer.setTitle("", for: .noMoreData)
                footer.setRefreshingTarget(self, refreshingAction: #selector(onFooterLoadMore))
            }

    //        底部处理逻辑：
            if pageIndex*13 < allCount {
                tableView.mj_footer.endRefreshing()
            }
            else {
                tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
    //        底部数据加载
             return tableView.mj_footer!
        }
    

        @objc func onHeaderRequery() {
            //        顶部数据重新加载
        }
        
        @objc func onFooterLoadMore() {
            //        底部数据重新加载更多底部处理逻辑：
            pageIndex += 1
            
            self.getSysqaList(lables: selLab, callback: { (sec,list) in
                if sec {
                    self.tableList = list
                    self.tableView.reloadData()
                }
            })
        }
}

extension M_HelperVC {
    
    ///MARK: UITableViewDelegate
    // 选中cell后执行此方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
        let vc = M_HelpDetail()
        let dic = tableList[indexPath.row]
        vc.detailDic = dic
        pushViewController(vc)
    }
    
    ///MARK: UITableViewDataSource
    
    //头部高度
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
       return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        let headView = UIView()
//        headView.backgroundColor = .white
//        headView.drawLabel(text: "常见问题", fontSize: 15, textColor: .x333333) { (make) in
//            make.left.equalTo(10)
//            make.centerY.equalToSuperview()
//        }
//        return headView
        return nil
    }
    
    //组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    
    // 设置cell高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 52
    }
    
    // cell的个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableList.count
    }
    
    // UITableViewCell
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cellid = "cell"
            var cell = tableView.dequeueReusableCell(withIdentifier: cellid)
            if cell==nil {
                cell = UITableViewCell(style: .default, reuseIdentifier: cellid)
                cell?.selectionStyle = .none
                //画横线
                let line = cell!.drawView { (make) in
                    make.left.equalToSuperview().offset(10)
                    make.right.equalToSuperview().offset(-10)
                    make.top.equalToSuperview()
                    make.height.equalTo(1)
                }
                line.backgroundColor = .xF2F2F2
                
                cell!.drawImage(named: "youjiantou_55") { (make) in
                    make.right.equalToSuperview().offset(-10)
                    make.centerY.equalToSuperview()
                }
            }
            let dic = tableList[indexPath.row]
            cell?.textLabel?.text = dic.getString("title")
            cell?.textLabel?.textColor = .x666666
            cell?.textLabel?.font = .italicSystemFont(ofSize: 12)
            return cell!
    }
}


// MARK: 事件
extension M_HelperVC {
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
}

///搜索词列表
class M_HelpLabList: UIView {
    
    //定义一个闭包类型
    typealias delBlock = () -> Void
    //声明一个变量
    var delBtnBack: delBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callDelBlock(block: @escaping delBlock) {
        delBtnBack = block
    }
    
    //定义一个闭包类型
    typealias moreBlock = () -> Void
    //声明一个变量
    var moreBtnBack: moreBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callMoreBlock(block: @escaping moreBlock) {
        moreBtnBack = block
    }
    
    //定义一个闭包类型
    typealias refreshBlock = () -> Void
    //声明一个变量
    var refreshBtnBack: refreshBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callRefreshBlock(block: @escaping refreshBlock) {
        refreshBtnBack = block
    }
    
    let titleLabel = UILabel()
    let btnDel = Button()
    let btnMore = Button()
    let tagsView = TagFlowView()
    var listAry = [String](){
        didSet{
            tagsView.isDirty = true
            tagsView.list = listAry
            tagsView.addTextBoxes()

            if refreshBtnBack != nil {
                refreshBtnBack!()
            }
        }
    }
    
    override func draw(_ rect: CGRect) {
//        tagsView.frame = CGRect(x: 10, y: 50, width: rect.width-20, height: rect.height-80)
        tagsView.width = rect.width-20
        self.addSubview(tagsView)
        tagsView.snp_makeConstraints{ (make) in
            make.left.equalTo(10)
            make.top.equalTo(50)
            make.width.equalToSuperview().offset(-20)
            make.height.equalToSuperview().offset(-60)
        }
        
//        对tagsView进行添加和布局

        tagsView.setProp(textFont: .systemFont(ofSize: 12), textColor: .x666666, horizontalPadding: 10, lineHeight: 25+5, horizontalMargin: 5, verticalMargin: 5, cornerRadius: 5, fillColor: .clear, borderColor: .x666666)
        tagsView.seltextColor = .white
        tagsView.selfillColor = .xFC4C02
        tagsView.selborderColor = .xFC4C02
        
        drawLabel(label: titleLabel, text: titleLabel.text, fontSize: 15, fontWeight: .medium, textColor: .x333333) { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(20)
        }
        
//        drawButton(button: btnDel,imageNamed: "shangchu_58") { (make) in
//            make.right.equalToSuperview().offset(-10)
//            make.top.equalToSuperview().offset(20)
//        }
//        btnDel.addTarget(self, action: #selector(onDelAction(button:)), for: .touchUpInside)
//        btnDel.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        
//        drawButton(button: btnMore,title: "", titleColor: .x999999, fontSize: 12) { (make) in
//            make.bottom.equalToSuperview().offset(-10)
//            make.centerX.equalToSuperview()
//        }
//        btnMore.addTarget(self, action: #selector(onMoreAction(button:)), for: .touchUpInside)
//        btnMore.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
    }
    
    @objc func onDelAction(button:UIButton){
        if delBtnBack != nil {
            delBtnBack!()
        }
    }
    
    @objc func onMoreAction(button:UIButton){
        if moreBtnBack != nil {
            moreBtnBack!()
        }
    }
}
